<template>
  <div id="operBroad">
    <div id="homeMap" class="btn_nav" title="初始地图">Origin</div>
    <div id="showWMS" class="btn_nav" title="显示WMS">WMS</div>
    <div id="showWMTS" class="btn_nav" title="显示WMTS">WMTS</div>
  </div>
  <div id="leftToolbox">
    <h1>CesiumJS</h1>
    <h2>DEMO</h2>
    <div id="addWFS" class="tool_">添加WFS</div>
    <div id="addWMS" class="tool_">添加WMS</div>
    <div id="addWMTS" class="tool_">添加WMTS</div>
    <div id="addTMS" class="tool_">添加TMS</div>
    <div id="add3dtiles" class="tool_">添加3DTiles</div>
    <div id="addTerrain" class="tool_">添加地形</div>
    <!-- <div id="changeSceneMode" class="tool_">维度设置</div> -->
  </div>
  <div id="changeSceneBroad">
    <div class="changeViewTitle">
      <h3>设置模式</h3>
    </div>
    <div id="change2D" class="changeView">2D 模式</div>
    <div id="change3D" class="changeView">3D 模式</div>
    <div id="changeColumbusView" class="changeView">2.5D模式</div>
  </div>
  <div id="container"></div>
</template>
 
<script setup>
import { onMounted } from 'vue'
import * as Cesium from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import './main.css'
import proj4 from 'proj4'
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0Y2YxYWFiOC1hMjkxLTQ3MmQtOTMzOC02ODQzNGYzZThjYmIiLCJpZCI6MTg0MTQwLCJpYXQiOjE3MDI0NDY4MDR9.Xax9xESQVAXXQgP_6OnWSj0AAvpwFh_FLQAxjdwfaZ0"
// const tdtKey = "c1edabc9c29f7eefef73ec71f3627b84";

onMounted(async () => {

  // 地球视图，底图加载
  const viewer = new Cesium.Viewer('container', {
    //地形图层
    // terrain: Cesium.Terrain.fromWorldTerrain(),
    infoBox: false,//信息窗口
    // geocoder: false,//显示查询按钮
    // homeButton: false,//home按钮
    sceneModePicker: false,//控制查看器的显示模式
    baseLayerPicker: false,// 是否显示图层选择
    navigationHelpButton: false, //帮助按钮
    animation: false,//播放动画
    timeline: false,//时间线
    fullscreenButton: false,//全屏模式
    showRenderLoopErrors: false,//关闭错误显示
    scene3DOnly: false,//关闭3D绘制
    // baseLayerPicker: false,//取消默认底图选择器
    // imageryProvider : false//蓝色地球
  });

  // cesium的默认视角
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(89.5, 20.4, 110.4, 61.2)

  //地图初始化
  function defaultMapSetting(viewer) {
    //隐藏cesium Icon-logo
    viewer.cesiumWidget.creditContainer.style.display = 'none';
    // 抗锯齿
    viewer.scene.fxaa = true;
    viewer.scene.postProcessStages.fxaa.enabled = false;
    // 水雾特效
    viewer.scene.globe.showGroundAtmosphere = true;
    // 设置最大俯仰角，[-90,0]区间内，默认为-30，单位弧度
    viewer.scene.screenSpaceCameraController.constrainedPitch = Cesium.Math.toRadians(-20);
    viewer.scene.screenSpaceCameraController.autoResetHeadingPitch = false;
    viewer.scene.screenSpaceCameraController.inertiaZoom = 0.5;
    //设置缩放程度
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 50;
    viewer.scene.screenSpaceCameraController.maximumZoomDistance = 30000000;
    //设置视角缩放类型
    viewer.scene.screenSpaceCameraController.zoomEventTypes = [
      Cesium.CameraEventType.RIGHT_DRAG,
      Cesium.CameraEventType.WHEEL,
      Cesium.CameraEventType.PINCH,
    ];
    //设置鼠标操作
    viewer.scene.screenSpaceCameraController.tiltEventTypes = [
      Cesium.CameraEventType.MIDDLE_DRAG,
      Cesium.CameraEventType.PINCH,
      {
        eventType: Cesium.CameraEventType.LEFT_DRAG,
        modifier: Cesium.KeyboardEventModifier.CTRL,
      },
      {
        eventType: Cesium.CameraEventType.RIGHT_DRAG,
        modifier: Cesium.KeyboardEventModifier.CTRL,
      },
    ];
    // 将三维球定位到中国
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(103.84, 31.15, 17850000),
      orientation: {
        heading: Cesium.Math.toRadians(348.4202942851978),
        pitch: Cesium.Math.toRadians(-89.74026687972041),
        roll: Cesium.Math.toRadians(0)
      },
      complete: function callback() {
        // 定位完成之后的回调函数
      }
    });
    // 添加cesium osm 建筑，3D楼房图层
    // const buildingTileset = await Cesium.createOsmBuildingsAsync();
    // viewer.scene.primitives.add(buildingTileset);
  }
  defaultMapSetting(viewer);

  // WFS坐标转换
  Cesium.GeoJsonDataSource.crsNames['urn:ogc:def:crs:EPSG::4490'] =
    Cesium.GeoJsonDataSource.crsNames['EPSG:4490'] = coordinates => {
      const fromProjection = `GEOGCS["China Geodetic Coordinate System 2000",DATUM["China_2000",SPHEROID["CGCS2000",6378137,298.257222101,AUTHORITY["EPSG","1024"]],AUTHORITY["EPSG","1043"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4490"]]`
      const toProjection = `GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]`

      const x = coordinates[0]
      const y = coordinates[1]

      const newCoordinates = proj4(fromProjection, toProjection, [x, y])
      return Cesium.Cartesian3.fromDegrees(
        newCoordinates[0],
        newCoordinates[1],
        0
      )
    }

  var clickFlag = 0;
  var skipFlag = [];
  //清除其他图层 显示原图层
  var btnOrginMap = document.getElementById("homeMap");
  btnOrginMap.addEventListener('click', function () {
    if (!viewer.imageryLayers.get.show) {
      console.log(skipFlag)
      console.log("clickflag:" + clickFlag);
      for (var i = 1; i <= clickFlag; i++) {
        if (i in skipFlag) {
          continue
        }
        viewer.imageryLayers.get(i).show = false;
      }
      viewer.imageryLayers.get(skipFlag[skipFlag.length - 1]).show = true;
      viewer.imageryLayers.get(0).show = true;
    }
  });

  //切换WMS底图
  var btnShowWMS = document.getElementById("showWMS");
  btnShowWMS.addEventListener('click', function () {
    viewer.imageryLayers.get(0).show = false;
    viewer.imageryLayers.addImageryProvider(
      new Cesium.WebMapServiceImageryProvider({
        url: "https://ows.terrestris.de/osm/service",
        layers: "OSM-WMS",
        // url: 'http://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer',
        // layers:"Layers"
      }),
    );
    clickFlag++;
  });

  //切换WMTS图层
  var btnShowWMTS = document.getElementById("showWMTS");
  btnShowWMTS.addEventListener('click', function () {
    viewer.imageryLayers.get(0).show = false;
    viewer.imageryLayers.addImageryProvider(
      new Cesium.WebMapTileServiceImageryProvider({
        url: "https://www.ign.es/wmts/ign-base",
        layer: "IGNBase-gris",
        style: "default",
        // format: "image/png",
        tileMatrixSetID: "GoogleMapsCompatible",
        // tileMatrixLabels: tileMatrixLabels,
        // tilingScheme: new Cesium.GeographicTilingScheme(),
      })
    );
    clickFlag++;
  });

  //添加WFS
  var btnAddWFS = document.getElementById("addWFS");
  btnAddWFS.addEventListener('click', function () {
    var urlWFS = prompt("请输入WFS服务地址:");
    if (urlWFS) {
      viewer.dataSources.add(Cesium.GeoJsonDataSource.load(urlWFS + "&outputformat=application/json"));
      clickFlag++;
      skipFlag.push(clickFlag);
    }
  });

  //添加WMS
  var btnAddWMS = document.getElementById("addWMS");
  btnAddWMS.addEventListener('click', function () {
    var urlWMS = prompt("请输入WMS服务地址:");
    var layersWMS = '';
    if (urlWMS) {
      var layername = urlWMS.split("%3A");
      if (!layername[1]) {
        layersWMS = prompt("请输入图层对应名称:");
      }
      else {
        layersWMS = layername[1];
      }
    }
    if (layersWMS) {
      viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapServiceImageryProvider({
          url: urlWMS,
          layers: layersWMS,
          parameters: {
            format: 'image/png',
            transparent: true,
            style: ''
          }
        })
      );
      clickFlag++;
      skipFlag.push(clickFlag);
    }

  });

  //添加WMTS
  var addWMTS = document.getElementById("addWMTS");
  addWMTS.addEventListener('click', function () {
    var urlWMTS = prompt("输入WMTS服务地址:");
    var layersWMTS = '';
    if (urlWMTS) {
      layersWMTS = urlWMTS.split("%3A");
      if (!layersWMTS[1]) {
        layersWMTS = prompt("输入WMTS图层名:");
      }
    }
    if (layersWMTS) {
      viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapServiceImageryProvider({
          url: urlWMTS,
          layers: layersWMTS,
          style: "default",
          tileMatrixSetID: "EPSG:4326"
        })
      );
      clickFlag++;
      skipFlag.push(clickFlag);
    }
  });

  //添加TMS
  var addTMS = document.getElementById("addTMS");
  addTMS.addEventListener('click', function () {
    var urlTMS = prompt("输入TMS服务地址:");
    if (urlTMS) {
      viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
          url: urlTMS + "/{z}/{x}/{y}.png",
        })
      );
      clickFlag++;
      skipFlag.push(clickFlag);
    }
  });

  //添加地形服务
  var addTerrain = document.getElementById("addTerrain");
  addTerrain.addEventListener('click', function () {
    var terrainlayerurl = prompt("请输入地形服务:")
    Cesium.CesiumTerrainProvider.fromUrl(terrainlayerurl, {
      requestWaterMask: true,
      requestVertexNormals: true,
    }).then((terrainProvider) => {
      viewer.terrainProvider = terrainProvider;
    });
  });

  //添加3dtiles服务
  var add3dtiles = document.getElementById("add3dtiles");
  add3dtiles.addEventListener('click', function () {
    let tiles_layer = prompt("请输入3dtiles服务地址:");
    Cesium.Cesium3DTileset.fromUrl(tiles_layer)
      .then((tileset) => {
        viewer.scene.primitives.add(tileset);
        viewer.zoomTo(tileset);
      })
      .catch((error) => {
        console.error("加载3DTiles数据集时出错:", error);
      });
  });

})
</script>
 
<style scoped></style>